package com.base.cn.platform.os.service.op.activity;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.order.OrderSource;
import com.base.cn.platform.os.common.utils.order.PayType;
import com.base.cn.platform.os.dao.op.activity.OpActivityDao;
import com.base.cn.platform.os.entity.op.activity.OpActivity;
import com.base.cn.platform.os.entity.op.coupon.OpCoupon;
import com.base.cn.platform.os.service.course.cou.CourseService;
import com.base.cn.platform.os.service.manage.subject.SysSubjectBiz;
import com.base.cn.platform.os.service.manage.user.SysUserBiz;
import com.base.cn.platform.os.service.op.coupon.OpCouponBiz;
import com.base.cn.platform.os.service.order.check.CreateOrderDataFrom;
import com.base.cn.platform.os.service.order.order.OrderBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 促销活动Biz
 * Created by ll on 2018/05/10.
 */
@Service
public class OpActivityBiz extends BaseBiz<OpActivity,OpActivityDao> {

    @Autowired
    private CourseService courseService;
    @Autowired
    private OpCouponBiz opCouponBiz;
    @Autowired
    private SysUserBiz sysUserBiz;
    @Autowired
    private SysSubjectBiz sysSubjectBiz;
    @Autowired
    private OrderBiz orderBiz;

    /**
     * 新建活动的添加保存
     *
     * @param activity
     * @return OpActivity
     */
    public OpActivity toAddOrUpdateActivity(OpActivity activity) {
        if (ObjectUtils.isNotEmpty(activity.getId())) {
            //添加时设置状态
            this.updateById(activity,null);
            return activity;
        } else {
            activity.setStatus(1);
            activity.setReleaseStatus(1);
            this.save(activity);
            return activity;
        }
    }

    /**
     * 促销活动的条件查询
     * @param activity 查询条件
     * @return
     */
    public String whereSql(OpActivity activity) {
        String whereSql = " 1=1 ";
        if (ObjectUtils.isNotEmpty(activity)) {
            if (StringUtils.isNotEmpty(activity.getActivityName())) {
                whereSql += " and activityName like  concat( '%','" + activity.getActivityName() + "','%')";
            }
            if (StringUtils.isNotEmpty(activity.getActivityType())) {
                whereSql += " and activityType  like  concat( '%','" + activity.getActivityType() + "','%')";
            }
            if (ObjectUtils.isNotEmpty(activity.getBeginTime())) {
                whereSql += " and createTime >= '" + new SimpleDateFormat("yyyy-MM-dd").format(activity.getBeginTime()) + "00:00:00'";
            }
            if (ObjectUtils.isNotEmpty(activity.getEndTime())) {
                String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(activity.getEndTime());
                whereSql += " and (beginTime <= '" + format + "' and endTime > '" + format + "')";
            }
            if (activity.getReleaseStatus()!=null&&activity.getReleaseStatus()>0) {
                whereSql += " and releaseStatus = " + activity.getReleaseStatus();
            }
            if (activity.getStatus()!=null&&activity.getStatus()>0) {
                whereSql += " and  status =" + activity.getStatus();
            } else {
                whereSql += " and  status  !=3";
            }
            if(StringUtils.isNotEmpty(activity.getSubjectIds())){
                whereSql += StringUtils.getSubjectSql("subjectIds",activity.getSubjectIds());
            }
        }
        whereSql += " order by id desc";
        return whereSql;
    }



    /**
     * 批量禁封登录，批量恢复
     *
     * @param activityIds 素材Id 字符串
     * @param status
     * @return
     */
    public void updateActivityStatusByIds(String activityIds, Integer status) {
        OpActivity activity = new OpActivity();
        activity.setStatus(status);
        this.updateByWhereSql(activity, " id in (" + activityIds + ")");
    }

    /**
     * 批量发布
     * @param activityIds   活动IDS
     * @param releaseStatus 发布状态
     */
    public void updateActivityReleaseStatusByIds(String activityIds, Integer releaseStatus) {
        OpActivity activity = new OpActivity();
        activity.setReleaseStatus(releaseStatus);
        this.updateByWhereSql(activity, " id in (" + activityIds + ")");
    }

    /**
     * 为活动课添加课程
     * @param activitys
     */
    public List<OpActivity> setCourseByActivityList(List<OpActivity> activitys) {
        if (ObjectUtils.isNotEmpty(activitys)) {
            String activityCourse = "";
            for (OpActivity activity : activitys) {
                if (StringUtils.isNotEmpty(activity.getCourseIds())) {
                    activityCourse += activity.getCourseIds();
                }
            }
            activityCourse =this.updateStringIds(activityCourse);
            if (StringUtils.isNotEmpty(activityCourse)){
                Map<BigDecimal, Map<String, Object>> courseMap = courseService.findCourseToMapByIds(activityCourse,false,false,false);
                if (ObjectUtils.isNotEmpty(courseMap)) {
                    List<BigDecimal> courseIdList = new ArrayList<>(courseMap.keySet());
                    for (OpActivity activity : activitys) {
                        List<Map<String, Object>> courseListMap = new ArrayList<>();
                        if (StringUtils.isNotEmpty(activity.getCourseIds())) {
                            for (BigDecimal courseId : courseIdList) {
                                if (activity.getCourseIds().contains(courseId.toString())) {
                                    courseListMap.add(courseMap.get(courseId));
                                }
                            }
                        }
                        activity.setCourse(courseListMap);
                    }
                }
            }
        }
        return activitys;
    }

    /**
     * 添加优惠券信息
     * @param activities
     */
    public List<OpActivity> setCouponByActivityList(List<OpActivity> activities) {
        if (ObjectUtils.isNotEmpty(activities)) {
            String activityCoupon = "";
            for (OpActivity activity : activities) {
                if (StringUtils.isNotEmpty(activity.getCouponIds())) {
                    activityCoupon += activity.getCouponIds();
                }
            }
            activityCoupon =this.updateStringIds(activityCoupon);
            if (StringUtils.isNotEmpty(activityCoupon)){
                if (StringUtils.isNotEmpty(activityCoupon)) {
                    List<OpCoupon> opCoupons = opCouponBiz.queryOpCouponByIds(activityCoupon, false,false,false,false);
                    Map<BigDecimal, OpCoupon> couponMap = opCoupons.stream().collect(Collectors.toMap(OpCoupon::getId, e -> e));
                    if (ObjectUtils.isNotEmpty(couponMap)) {
                        List<BigDecimal> couponIdList = new ArrayList<>(couponMap.keySet());
                        for (OpActivity activity : activities) {
                            List<OpCoupon> couponList = new ArrayList<>();
                            if (StringUtils.isNotEmpty(activity.getCouponIds())) {
                                for (BigDecimal couponId : couponIdList) {
                                    if (activity.getCouponIds().contains(couponId.toString())) {
                                        couponList.add(couponMap.get(couponId));
                                    }
                                }
                            }
                            activity.setCoupons(couponList);
                        }
                    }
                }
            }
        }
        return activities;
    }

    /**
     * 单个添加扩展数据
     * @param opActivitie
     * @param courseData
     * @param couponData
     * @param createUserData
     * @return
     */
    public OpActivity setCouponAndCourseAndSysUser(OpActivity opActivitie,boolean courseData,boolean couponData,boolean createUserData,boolean subjectData){
        List<OpActivity> opActivities = new ArrayList<>();
        opActivities.add(opActivitie);
        opActivities = this.setCouponAndCourseAndSysUserList(opActivities,courseData,couponData,createUserData,subjectData);
        return opActivities.get(0);
    }

    /**
     * 添加扩展数据
     * @param opActivities
     * @param courseData
     * @param couponData
     * @param createUserData
     * @return
     */
    public List<OpActivity> setCouponAndCourseAndSysUserList(List<OpActivity> opActivities,boolean courseData,boolean couponData,boolean createUserData,boolean subjectData){
        if (ObjectUtils.isNotEmpty(opActivities)){
            if (courseData){
                opActivities = this.setCourseByActivityList(opActivities);
            }
            if (couponData){
                opActivities = this.setCouponByActivityList(opActivities);
            }
            if(createUserData){
                sysUserBiz.setSysUserData(opActivities,createUserData);
            }
            if (subjectData){
                sysSubjectBiz.setSubjectData(opActivities,subjectData);
            }
        }
        return opActivities;
    }

    /**
     * 分页查询活动
     * @param opActivitie
     * @param page
     * @param courseData
     * @param couponData
     * @param createUserData
     * @return
     */
    public PageInfo<OpActivity> queryOpActivityListPage(OpActivity opActivitie, Pagination page, boolean courseData, boolean couponData, boolean createUserData, boolean subjectData){
        String where = whereSql(opActivitie);
        PageInfo<OpActivity> pageInfo = this.findPage(where,page,null);
        List<OpActivity> opActivities = pageInfo.getList();
        opActivities =setCouponAndCourseAndSysUserList(opActivities,courseData,couponData,createUserData,subjectData);
        pageInfo.setList(opActivities);
        return pageInfo;
    }


    /**
     * 搜索活动
     * @param opActivity
     * @return
     */
    public List<OpActivity> queryOpActivityList(OpActivity opActivity,boolean courseData, boolean couponData, boolean createUserData,boolean subjectData) {
        String whereSql = this.whereSql(opActivity);
        List<OpActivity> opActivities =this.find(whereSql,null,null);
        return setCouponAndCourseAndSysUserList(opActivities,courseData,couponData,createUserData,subjectData);
    }

    /**
     * 根据Id搜索活动
     * @param activityId
     * @param courseData
     * @param couponData
     * @param createUserData
     * @param subjectData
     * @return
     */
    public OpActivity queryOpActivityById(BigDecimal activityId,boolean courseData, boolean couponData, boolean createUserData,boolean subjectData){
        OpActivity opActivity = this.findById(activityId);
        return setCouponAndCourseAndSysUser(opActivity,courseData,couponData,createUserData,subjectData);
    }

    /**
     * 查询订单可用的活动（只用于存在课程商品的订单）
     * @param paramsList 限制条件
     * @param courseData 是否设置课程
     * @return List<OpActivity>
     */
    public List<OpActivity> findOrderAvailableActivityList(List<Map<String,String>> paramsList,boolean courseData) {
        StringBuffer stringBuffer = new StringBuffer("`status` =1 and beginTime <= now() and endTime >= now()");
        if(ObjectUtils.isNotEmpty(paramsList)){
            double price = paramsList.stream().mapToDouble(e->Double.parseDouble(e.get("price"))).sum();
            stringBuffer.append(" and ").append(price).append(" >= askAmount");
        }
        List<OpActivity> opActivities = this.find(stringBuffer.toString(), null, null);
        if(courseData){
            this.setCourseByActivityList(opActivities);
        }
        return opActivities;
    }


    //====================================================================================
    /**
     * 处理Id串
     * @param string
     * @return
     */
    private String updateStringIds(String string){
        String str = "";
        if (StringUtils.isNotEmpty(string)) {
            String[] courseIdArray = string.split(",");
            if (ObjectUtils.isNotEmpty(courseIdArray)) {
                for (String ids : courseIdArray) {
                    if (StringUtils.isNotEmpty(ids) && !str.contains(ids)) {
                        str += ids + ",";
                    }
                }
            }
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }

    /**
     * 参加活动免费赠送课程
     *
     * @param userId
     * @param activityId
     */
    @Transactional(rollbackFor = IllegalArgumentException.class)
    @Async
    public void giveFreeCourseActivity(BigDecimal userId,BigDecimal activityId){
        if (DataUtil.idIsNotNull(userId) && DataUtil.idIsNotNull(activityId)){
            OpActivity opActivity = this.queryOpActivityById(activityId, false, false, false, false);
            String courseIds = opActivity.getCourseIds();
            if(StringUtils.isNotEmpty(courseIds)){
                String _courseIds = StringUtils.subHeadTailString(courseIds, ",");
                String[] split = _courseIds.split(",");
                String shopData = Arrays.stream(split).collect(Collectors.joining("-COURSE-1,","","-COURSE-1"));
                try {
                    CreateOrderDataFrom createOrderDataFrom = new CreateOrderDataFrom();
                    createOrderDataFrom.setShopData(shopData);
                    createOrderDataFrom.setUserId(userId);
                    createOrderDataFrom.setAutoGive(true);//设置成系统自动赠送
                    createOrderDataFrom.setPayType(PayType.PAY_TYPE_ADMIN_FREE);
                    createOrderDataFrom.setOrderForm(OrderSource.ORDER_FORM_ADMIN);
                    orderBiz.createFreeOrder(createOrderDataFrom);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
